<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 9:45:22
 * Info:
 */

namespace app\common\model;

use app\common\service\admin\AuthService;
use think\facade\Db;

class Admin extends TimeInit
{

    /**
     * 获取管理员列表
     *
     * @param $params
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminList($params = [])
    {
        $data = [];
        if ($params) {
            $limit = $params['limit'];
            $first = $params['first'];
            $field = $params['field'];
            $order = $params['order'];
            $key   = $params['key'];
            //取出当前管理员所拥有权限的分组
            $role_id          = AuthService::getChildrenGroupIds(true);
            $childrenAdminIds = AuthService::getChildrenAdminIds(true);
            //获取sql条件
            $where = function ($query) use ($key, $role_id, $childrenAdminIds) {
                $query->where('id', 'in', $childrenAdminIds);
                if ( ! empty($key['username'])) {
                    $query->whereLike('username', '%'.$key['username'].'%');
                }
                if ( ! empty($key['role_id'])) {
                    $uids = AuthGroupAccess::where('group_id', $key['role_id'])->column('uid');
                    $query->whereIn('id', $uids);
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
            };
            $count = Admin::where($where)->count();
            $list  = Admin::where($where)->limit($first, $limit)->order($field, $order)->select();
            foreach ($list as $key => $v) {
                $group_list  = AuthService::getGroups($v['id']);
                $group_list1 = array_column($group_list->toArray(), 'name');

                $list[$key]['logintime']  = date('Y-m-d H:i:s', $v['logintime']);
                $list[$key]['group_name'] = implode(',', $group_list1);
            }
            $data['list']  = $list ?? [];
            $data['count'] = $count ?? [];
        }

        return $data;
    }

    /**
     * 更新后台登录失败次数
     *
     * @param $adminId
     * @param $failure
     *
     * @return void
     */
    public static function editLoginFailure($adminId, $failure = 0)
    {
        if (empty($adminId)) {
            return false;
        }
        if ($failure) {
            self::where(['id' => $adminId])->update([
                'logintime'     => time(),
                'update_time'   => time(),
                'login_failure' => Db::raw('login_failure+1')
            ]);

            return true;
        } else {
            self::where(['id' => $adminId])->data(['login_failure' => 0])->update();

            return true;
        }
    }

}
